package com.hx.vending.service.impl;


import com.hx.vending.bean.CapitalFlow;
import com.hx.vending.bean.User;
import com.hx.vending.bean.UserWithdraw;
import com.hx.vending.dao.CapitalFlowMapper;
import com.hx.vending.dao.UserMapper;
import com.hx.vending.dao.UserWithdrawMapper;
import com.hx.vending.service.IDrawCashService;
import com.hx.vending.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/12/29.
 * 提现申请
 */
@Service
public class DrawCashServiceImpl implements IDrawCashService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private CapitalFlowMapper capitalFlowMapper;

    @Resource
    private UserWithdrawMapper userWithdrawMapper;


    /**
     * 商户申请提现
     * @param userId
     * @param money
     * @return
     */
    public Msg insertApplyForDrawCash(Integer userId, Double money,Integer type) {

        if (ToolUtil.isNotEmpty(userId) && ToolUtil.isNotEmpty(money)) {

            //查询用户信息
            User user = new User();
            user.setUserId(userId);
            User selectUser = this.userMapper.selectByPrimaryKey(user);

            /*if (ToolUtil.isEmpty(selectUser.getUserLegalPersonIdCard()) || ToolUtil.isEmpty(selectUser.getUserBankAccountNo()) || ToolUtil.isEmpty(selectUser.getUserAccount())) {
                return Msg.fail().add("msg", "未填写工商资料！！");
            }*/
            String out_biz_no = DateUtil.getAllTime()+ToolUtil.generateNonceStr(4);
            if (ToolUtil.isNotEmpty(selectUser) && selectUser.getUserMoney() >= money) {
                Float float1 = selectUser.getUserWithdrawproportion();//// 商户提现比例
                double double1 = Double.parseDouble(float1.toString());
                double pool = BigDecimalUtils.mul(money, double1 / 100);// 手续费
                pool = BigDecimalUtils.round(Math.ceil(pool*100), 100, 2);//手续费
                //实际到账金额
                double subMoney = BigDecimalUtils.sub(money, pool);// 提现减去提现手续费
                UserWithdraw userWithdraw = new UserWithdraw();
                userWithdraw.setUserWithdrawUserid(userId);
                userWithdraw.setUserWithdrawOutBizNo(out_biz_no);
                userWithdraw.setUserWithdrawMoney(money);
                userWithdraw.setUserWithdrawPractical(subMoney);
                //userWithdraw.setUserWithdrawBankName(selectUser.getB);
                userWithdraw.setUserWithdrawBankNumber(selectUser.getUserBankAccountNo());
                userWithdraw.setUserWithdrawTime(DateUtil.getTime());
                userWithdraw.setUserWithdrawType(type);
                userWithdraw.setUserWithdrawBankNumber(selectUser.getUserBankAccountNo());
                userWithdraw.setUserWithdrawRemark("提现中");
                userWithdraw.setUserWithdrawState(1);

                //提现后，扣除用户余额
                Double money1 = BigDecimalUtils.sub(selectUser.getUserMoney(), money);
                user.setUserMoney(money1);
                if(type == 2){
                    user.setUserWechatBalance(BigDecimalUtils.sub(selectUser.getUserWechatBalance(),money));
                }else if(type == 3){
                    user.setUserAlipayBalance(BigDecimalUtils.sub(selectUser.getUserAlipayBalance(),money));
                }
                this.userMapper.updateByPrimaryKeySelective(user);
                CapitalFlow capitalFlow = new CapitalFlow();
                capitalFlow.setCapitalFlowUserId(selectUser.getUserId());
                capitalFlow.setCapitalFlowUserMoney(money);
                capitalFlow.setCapitalFlowTransactionAmount(money);
                capitalFlow.setCapitalFlowPaymentType(3);//银行卡
                capitalFlow.setCapitalFlowTransactionType(1);//代理商提现
                capitalFlow.setCapitalFlowTime(DateUtil.getTime());
                capitalFlow.setCapitalFlowState(1);//完成
                capitalFlow.setCapitalFlowRemarks("代理商提现");
                capitalFlow.setCapitalFlowTransactionNumber(out_biz_no);//订单号
                //添加流水
                this.capitalFlowMapper.insertSelective(capitalFlow);
                CapitalFlow c = capitalFlowMapper.selectByPrimaryKeySelective(capitalFlow);
                /*drawCash.setDrawCashFlowId(c.getCapitalFlowId());
                //添加提现申请
                int i = this.drawCashMapper.insertSelective(drawCash);*/
                userWithdraw.setUserWithdrawFlowId(c.getCapitalFlowId());
                int i = userWithdrawMapper.insertSelective(userWithdraw);
                if(i > 0){
                    return Msg.success();
                }else{
                    return Msg.fail();
                }
            }else if(ToolUtil.isNotEmpty(selectUser) && selectUser.getUserMoney() < money){
                return Msg.fail().add("msg","余额不足");
            }
        }else {
            return Msg.fail().add("msg", "当前用户不存在!!");
        }
        return Msg.fail();
    }


    /**
     * 后台查询提现申请
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Msg selectDrawCash(Integer pageNum, Integer pageSize) {

        Integer pageStart = (pageNum - 1) * 10;
        Map<String,Object> map = new HashMap<>();
        map.put("pageStart",pageStart);
        map.put("pageSize",pageSize);
        List<UserWithdraw> userWithdrawList = userWithdrawMapper.selectByExampleBack(map);
        return Msg.success().add("pageInfo", userWithdrawList);
    }


    /**
     * 后台同意提现
     * @param userWithdrawId
     * @return
     */
    public Msg updateAgreeDrawCash(Integer userWithdrawId) {

        if (ToolUtil.isNotEmpty(userWithdrawId)) {

            //查询提现信息
           UserWithdraw userWithdraw = new UserWithdraw();
           userWithdraw.setUserWithdrawId(userWithdrawId);
           UserWithdraw selectUserWithdraw = userWithdrawMapper.selectByPrimaryKey(userWithdraw);
           userWithdraw.setUserWithdrawRemark("提现成功");
           userWithdraw.setUserWithdrawAccount(DateUtil.getTime());
            userWithdraw.setUserWithdrawState(2);
            //drawCash.setDrawCashState(1);
            //int i = this.drawCashMapper.updateByPrimaryKeySelective(drawCash);
            int i = userWithdrawMapper.updateByPrimaryKeySelective(userWithdraw);
            Double pool = BigDecimalUtils.sub(selectUserWithdraw.getUserWithdrawMoney(),selectUserWithdraw.getUserWithdrawPractical());
            User u = new User();
            u.setUserId(selectUserWithdraw.getUserWithdrawUserid());
            User user = userMapper.selectByPrimaryKey(u);
            if(user.getUserTxPush().equals("1")){
                //提现推送
                String pushMessage = "商户提现订单:\n提现商户:%s\n订单状态:提现成功\n提现金额:%s\n提现手续费:%s\n实际提现金额:%s\n当前余额:%s\n提现时间:%s";
                try {
                    PushUtils.getInstance().pushMessage(user.getUserAccount(), String.format(pushMessage,
                            user.getUserName(),
                            selectUserWithdraw.getUserWithdrawMoney(),
                            pool,
                            selectUserWithdraw.getUserWithdrawPractical(),
                            user.getUserMoney(),
                            DateUtil.getTime()
                    ));
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            if(i > 0){
                CapitalFlow capitalFlow = new CapitalFlow();
                capitalFlow.setCapitalFlowId(selectUserWithdraw.getUserWithdrawFlowId());
                capitalFlow.setCapitalFlowState(2);
                int j = this.capitalFlowMapper.updateByPrimaryKeySelective(capitalFlow);
                if(j > 0){
                    return Msg.success();
                }
            }
            return Msg.fail();
        }else {
            return Msg.fail();
        }

    }

    @Override
    public Msg notAgreeDrawCash(Integer userWithdrawId) {
        if(ToolUtil.isNotEmpty(userWithdrawId)){
            //查询提现信息
           UserWithdraw userWithdraw = new UserWithdraw();
           userWithdraw.setUserWithdrawId(userWithdrawId);
           UserWithdraw selectUserWithdraw = userWithdrawMapper.selectByPrimaryKey(userWithdraw);
           userWithdraw.setUserWithdrawRemark("提现失败");
            userWithdraw.setUserWithdrawState(0);
            // d.setDrawCashState(2);
            //int i = this.drawCashMapper.updateByPrimaryKeySelective(d);
            int i = userWithdrawMapper.updateByPrimaryKeySelective(userWithdraw);
            if(i > 0){
                //用户信息
                User u = new User();
                u.setUserId(selectUserWithdraw.getUserWithdrawUserid());
                User user = userMapper.selectByPrimaryKey(u);
                u.setUserMoney(BigDecimalUtils.add(user.getUserMoney(),selectUserWithdraw.getUserWithdrawMoney()));
                if(selectUserWithdraw.getUserWithdrawType() == 2){
                    u.setUserWechatBalance(BigDecimalUtils.add(user.getUserWechatBalance(),selectUserWithdraw.getUserWithdrawMoney()));
                }else if(selectUserWithdraw.getUserWithdrawType() == 3){
                    u.setUserAlipayBalance(BigDecimalUtils.add(user.getUserAlipayBalance(),selectUserWithdraw.getUserWithdrawMoney()));
                }
                userMapper.updateByPrimaryKeySelective(u);

                CapitalFlow capitalFlow = new CapitalFlow();
                capitalFlow.setCapitalFlowId(selectUserWithdraw.getUserWithdrawFlowId());
                capitalFlow.setCapitalFlowState(3);
                int j = this.capitalFlowMapper.updateByPrimaryKeySelective(capitalFlow);
                if(j > 0){
                    return Msg.success();
                }
            }
        }
        return Msg.fail();
    }


}
